package org.infinitest.swingui;

import static org.hamcrest.Matchers.*;
import static org.infinitest.EventFakeSupport.*;
import static org.junit.Assert.*;

import java.awt.Component;
import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

import junit.framework.AssertionFailedError;

import org.junit.Before;
import org.junit.Test;

public class WhenShowingMainFrame
{
  private FailureCellRenderer cellRenderer;
  private InfinitestMainFrame mainFrame;
  private Component focusedComponent;

  @Before
  public void inContext()
  {
    mainFrame = new InfinitestMainFrame();
    cellRenderer = (FailureCellRenderer) mainFrame.getTree().getCellRenderer();
  }

  @Test
  public void shouldHaveTooltipToInformUsersAboutClickFunctionality() throws Exception
  {
    assertEquals("Double-click test nodes for more info", cellRenderer.getToolTipText());
  }

  @Test
  public void shouldStartWithTreeFocused() throws Exception
  {
    TreeFocusListener listener = new TreeFocusListener()
    {
      @Override
      protected void setFocus(Component c)
      {
        focusedComponent = c;
      }
    };
    listener.windowGainedFocus(new WindowEvent(mainFrame, 0));
    assertEquals(mainFrame.getTree(), focusedComponent);

    // This doesn't work
    // assertTrue(mainFrame.getTree().hasFocus());
  }

  @Test
  public void shouldHaveIconToIndicatePoFNodes() throws Exception
  {
    Object node = "PointOfFailure.java:32";
    JLabel treeCell = (JLabel) cellRenderer.getTreeCellRendererComponent(mainFrame.getTree(), node, false, false, false, 0, false);
    assertThat(treeCell.getIcon().toString(), is(expectedIcon("error")));
  }

  @Test
  public void shouldHaveIconToIndicateFailingTest() throws Exception
  {
    Object node = eventWithError(new AssertionFailedError());
    JLabel treeCell = (JLabel) cellRenderer.getTreeCellRendererComponent(mainFrame.getTree(), node, false, false, false, 0, false);
    assertThat(treeCell.getIcon().toString(), is(expectedIcon("failure")));
  }

  private String expectedIcon(String iconName)
  {
    ImageIcon expectedIcon = new ImageIcon(FailureCellRenderer.class.getResource("/org/infinitest/swingui/" + iconName + ".png"));
    return expectedIcon.toString();
  }
}
